//var Browser = new Object();
//
//Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument != 'undefined');
//Browser.isIE = window.ActiveXObject ? true : false;
//Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") != - 1);
//Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != - 1);
//Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != - 1);

var Cookies = {};
/**//**
 * 设置Cookies
 */
Cookies.set = function(name, value, expires){
     var argv = arguments;
     var argc = arguments.length;
	var date = new Date();
	date.setTime(date.getTime()+1000 * expires);
	var expirestr = date.toGMTString();
	//var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       expirestr +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};
/**//**
 * 读取Cookies
 */
Cookies.get = function(name){
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    var j = 0;
    while(i < clen){
        j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return Cookies.getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if(i == 0)
            break;
    }
    return null;
};
/**//**
 * 清除Cookies
 */
Cookies.clear = function(name) {
  if(Cookies.get(name)){
    var expdate = new Date(); 
    expdate.setTime(expdate.getTime() - (86400 * 1000 * 1)); 
    Cookies.set(name, "", expdate); 
  }
};

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
};

var util = {};
util.ready =function(){
	util.toggleMenu();
//	util.toggleAdvanceSearch();
	util.extendValidateType();
	util.formatteDateBox();
//	util.setAutoComplete();
//	util.extendGridEditor();
};

util.parseText = function(value){
	var text = value;
	text = value.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return text;
}

util.addTipForGridCell = function(value,tip){
	var html = "<div style='position:relative;'><div style=';width:100%' onMouseOver='util.showTip(\""+tip+"\")' onMouseOut='util.hideTip()'>"+value+"</div></div>";
	return html;
}

/*
 * {
 *  name:value,
 *  tip:tip,
 *  showInfo:id}
 */
util.formatteGoodsNameForGridCell = function(options){
	var value = options.name;
	var tipHtml = "";
	var showInfoHtml = "";
	var tip = options.tip
	var goodsid = options.showInfo;
	if(tip){
		tipHtml = "onMouseOver='util.showTip(\""+tip+"\")' onMouseOut='util.hideTip()'";
	}
	if(goodsid){
		showInfoHtml = "class='bluelink' onClick='window.location.href=\""+context+"/b2b/goods!showGoodsInfo.action?id="+goodsid+"\";'";
	}
	var html = "<div style='position:relative;color:blue;'><div style=';width:100%'"+tipHtml+" "+showInfoHtml+" >"+value+"</div></div>";
	return html;
}

util.tip = {time:null,objTip:null};

util.showTip = function(tip){
	var e = util.getEvent();
	var point = {x:0,y:0};
    var a = document.documentElement.scrollLeft;
    var b = document.documentElement.scrollTop;
	point.x=e.clientX+a+15; 
	point.y=e.clientY+b+15; 
	var divTip = $('<div id="goods_tip" class="tip" style=";position:absolute;left:'+point.x+'px;top:'+point.y+'px;";><div class="tip_le"></div><div class="tip_con">'+tip+'</div><div class="tip_ri"></div></div>');
	util.tip.objTip = divTip;
	util.tip.time = setTimeout(function(){
		divTip.appendTo('body');
		util.tip.time = null;
	},100);
}
util.hideTip = function(){
	if(util.tip.time){
		clearTimeout(util.tip.time);
	}
	else {
		$('#goods_tip').remove();
	}
}


util.GRID_OPTIONS = {
	 width:768,
	 border:true,
	 striped: true,//行与行之间颜色区分
	 loadMsg:'正在加载数据,请等待...',
	 //fitColumns: true,
	 onLoadSuccess: function(data){
	    if($(this).attr('pagination')){
	  	  var dom_pagination = $('#'+$(this).attr('pagination')+'');
	  	  var total = data.total;
	  	  dom_pagination.pagination(this,total);
	    } 
     },
     onLoadError: function(){
    	 //alert('error');
     }
}

//已经存在的默认的验证有,email,url,length[min,max];
util.extendValidateType = function(){
	$.fn.validatebox.defaults.rules.url.message = "请输入合法的URL.";
	$.fn.validatebox.defaults.rules.email.message = "请输入合法的Email.";
	$.fn.validatebox.defaults.rules.length.message = "输入的值的长度必须为{0}到{1}";
	$('.easyui-validatebox').each(function(){
		$(this).validatebox({
			missingMessage:"该值不可为空"
		});
	});
	$.extend($.fn.validatebox.defaults.rules, {
		text:{
			validator:function(value,params){
				var reg=/^[0-9a-zA-Z_\u4e00-\u9fa5]+$/;
				return reg.test(value);
	        },
	        message:'您输入的内容含有非法字符'
	    },
	    number:{//由数字组成的串
			validator:function(value,params){
			  var reg = /^\d+$/;
			  return reg.test(value);
		    },
		    message:'请输入数字'
	    },
	    date:{
	    	validator:function(value){
	    	     var time = value.replace(/[ ]/g,"");
	    	     var reg = /^(1|2)[0-9]{3}-((0[1-9])|10|11|12)-((0[1-9])|([1|2][0-9])|30|31)$/;//一般时间验证
	    	     if(!reg.test(time)){
	    	    	 return false;
	    	     }
	    	     else {
	    	    	 var year = time.substring(0,4);
	    	    	 var yearNum = parseInt(year);
		    	     var month = time.substring(5,7);
		    	     var monthNum = parseInt(month,10);
		    	     var date = time.substring(8);
		    	     var dateNum = parseInt(date,10);
		    	     return util.checkDate(yearNum, monthNum, dateNum);
	    	     }
	       },
	       message:"请输入合法的时间"
	    },
	    phone:{
	      validator:function(value){
	        	var reg = /^[\d|\-|\s|\_]+$/; //只允许使用数字-空格等
	        	return reg.test( value );
	      },
	      message:"请输入合法的电话号码"
	    },
	    positive:{//正数(保留2位小数)
	    	validator:function(value){
	    	    var reg = /^(0|[1-9][0-9]*)(\.[0-9]{0,2})?$/;
	    	    return reg.test(value);
	        },
	        message:"请输入合法的数字"
	    },
	    positiveInteger:{//正整数
	    	validator:function(value){
	    	    var reg = /^[1-9][0-9]*$/;
	    	    return reg.test(value);
	        },
	        message:"请输入合法的正整数"
	    },
	    remoteValidate:{
	    	validator:function(value,remoteResult){
	    	      return remoteResult[0];
	        },
	        message:""
	    },
	    confirmValue:{
	    	validator:function(value,params){
	    	     return value == params[0];
	        },
	        message:""
	    },
	    range:{
	        validator:function(value,params){
	    	      return (value > params[0] && value < params[1]);
	        },
	        message:"请输入{0}到{1}之间的值"
	    },	     
		stringNoValue:{
		   validator:function(value,param){
			  var reg = /^[A-Za-z0-9\u4e00-\u9fa5_-]*$/;
			  ret = reg.test(value);
			  if(param[0]){ 
			  	ret =ret && value.length >= param[0] &&  value.length <= param[1];
			  }
			  return ret;
		    },
		    message:'请输入正确的内容格式,长度{0}-{1}'
	    },
	    lengthNumber:{ 
			validator:function(value,param){
			  var reg = /^\d+$/;
			  ret = reg.test(value);
			  if(param[0]){ 
			  	ret =ret && value.length >= param[0] &&  value.length <= param[1];
			  }
			  return ret;
		    },
		    message:'请输入正确的数字{0}-{1}'
	    },
	    lengthURL:{ 
			validator:function(value,param){
			  var reg = /^http:\/\/[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)+$/;
			  ret = reg.test(value);
			  if(param[0]){ 
			  	ret =ret && value.length >= param[0] &&  value.length <= param[1];
			  }
			  return ret;
		    },
		    message:'请输入正确的网址{0}-{1}'
	    }
	    
	});

};
util.extendGridEditor = function(){
   $.extend($.fn.datagrid.defaults.editors, {
    number: {
        init: function(container, options){
            var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
            input.bind('keydown',function(event){
            	var value = input.val();
            	var code = event.keyCode;
            	var hasDot = value.indexOf('.');
            
            	if(value){
            		if(code > 58 || code < 48 && code != 8 && code !=37 && code !=39 &&code != 13){
  
            			if(hasDot == -1 && code == 190){
                			         		
                		}
            			else {
            				return false;
            			}
            		}
            	}
            	else {
            		if(code > 58 || code < 48  && code != 8 && code !=37 && code !=39&&code != 13){
            			return false;
            		}
            	}
            });
            return input;
        },
        getValue: function(target){
        	var value = $(target).val();
        	if(value[value.length-1] == '.'){
        		value = value.slice(0,value.length-1);
        	}
            return value;
        },
        setValue: function(target, value){
        	if(value&&value[value.length-1] == '.'){
        		value = value.slice(0,value.length-1);
        	}
            $(target).val(value);
        },
        resize: function(target, width){
            var input = $(target);
            if ($.boxModel == true){
                input.width(width - (input.outerWidth() - input.width()));
            } else {
                input.width(width);
            }
        }
    }
});
}
util.checkFormFields = function(form){
	return $(form).form('validate');
}

util.checkDate = function(year,month,date){
	if(month > 12 || month < 1) return false;
	if(date > 31 || date < 1) return false;
	var leap = util.isLeapYear(year);
	if(month == 2){
		if(leap && date >29) return false;
		else if(!leap && date >28) return false;
		else return true;
	}
	else if((month == 4|| month == 6 || month == 9|| month == 11)&& date > 30){
		return false;
	}
	else return true;
}

util.isLeapYear = function(year){
	if(year%4 == 0 && year%100 != 0 || year%400 == 0){
   	   return true;
    }
	return false;
}

util.toggleMenu = function(){
	$('#qg_menu .toggle').each(function(){
		var me = this;
//		$('img',$(this)).toggle(function(){
//			$(this).attr('src',context+'/img/menu_title_ribot.gif');
//			$(me).next().slideUp("normal");
//		},function(){
//			$(this).attr('src',context+'/img/menu_title_ritop.gif');
//			$(me).next().slideDown("normal");
//		});
		$(this).toggle(function(){
			$('img',$(this)).attr('src',context+'/img/menu_title_ribot.gif');
			$(this).next().slideUp("normal");
		},function(){
			$('img',$(this)).attr('src',context+'/img/menu_title_ritop.gif');
			$(this).next().slideDown("normal");
		});
	});
}

util.toggleAdvanceSearch = function(){
	if($('.advance_search')){
		$('.advance_search').each(function(){
			var me = this;
			var target = $(me).attr('toggle');
			
			$(me).toggle(function(){
				$('#'+target+'').show(0);
				$('img',this).attr('src',context+'/img/shanxuan_top.gif');
			},function(){
				$('#'+target+'').hide(0);
				$('img',this).attr('src',context+'/img/shanxuan_left.gif');
			});
		})
	}
}

util.getEventTarget = function(event){
	var event = util.getEvent();
	var target = event.srcElement ? event.srcElement : event.target;
	return target;
}

util.search = function(gridId,customisefilters,customizable){
	var ev = util.getEvent();
	if(ev){
		var target = util.getEventTarget(ev);
		$(target).attr('disabled','true');
		setTimeout(function(){$(target).attr('disabled','');}, 5000);
	}
	
	var grid = $('#'+gridId+'');
	grid.datagrid('clearSelections');
	var options = grid.datagrid('options');
	var pagination = $('#'+grid.attr('pagination')+'');
	options.queryParams = {};
	if(!customizable){
		var dom_filters = $('#'+grid.attr('filter')+'');
		var _filters = $('*[name^=filter]',dom_filters);
		$.each(_filters,function(index,filter){
			options.queryParams[filter.name] = filter.value;
		});
	}
	if(customisefilters){
		for(prop in customisefilters){
			options.queryParams[prop] = customisefilters[prop];
		}
	}
	options.queryParams.pageNum = 1;
	if(pagination){
		pagination.get(0).currentPage = 1;
	}
	grid.datagrid('reload');
};

util.setEnable = function(target, enable){
	$(target).attr('disabled',enable);
}

util.checkRepeatSubmit = function(){
	var cn = $('input[name=struts.token]').val();
	if(Cookies.get(cn)) {
		alert("此页面不应该多次提交！");
		return false;
	} else {
		Cookies.set(cn, "yes", 60);
		return true;
	}
}

util.remove = function(gridId,url,deleteEntityIds){
	var grid = $('#'+gridId+'');
	var param = {ids:''};
	if(deleteEntityIds){
		param.ids = deleteEntityIds;
	}
	else {
		var selections = grid.datagrid('getSelections');
		$.each(selections,function(index,selection){
			if(!param.ids){
				param.ids = param.ids+selection.id;
			}
			else {
				param.ids = param.ids+","+selection.id;
			}
		})
	}
	$.ajax({
		url:url,
		data:param,
		success:function(){
		    grid.datagrid('reload');
	    }
	});
};



util.formatteDateBox = function(){
	var datebox = $('.datebox');
	if(datebox.size()>0){
		$.each(datebox,function(){
			$(this).datebox({
				currentText:"今天",
				closeText:"关闭",
				missingMessage:"该值不可为空",
				formatter: function(date){
				   var year = date.getFullYear();
				   var month = date.getMonth()+1;
				   if(month<10){
					   month = "0"+month+"";
				   }
				   var date = date.getDate();
				   if(date<10){
					   date = "0"+date+"";
				   }
				   return year+'-'+month+'-'+date+'';
			    }
			})
		})
		
	}
}


util.htmlEncode = function(text)
{
  return text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

util.trim = function( text )
{
  if (typeof(text) == "string")
  {
    return text.replace(/^\s*|\s*$/g, "");
  }
  else
  {
    return text;
  }
}

util.isEmpty = function( val )
{
  switch (typeof(val))
  {
    case 'string':
      return util.trim(val).length == 0 ? true : false;
      break;
    case 'number':
      return val == 0;
      break;
    case 'object':
      return val == null;
      break;
    case 'array':
      return val.length == 0;
      break;
    default:
      return true;
  }
}

util.setAutoComplete = function(){
	var doms = $('.autoComplete');
	if(doms.size()>0){
		$.each(doms,function(index,dom){
			util.autoComplete(dom);
		})
	}
}

util.autoComplete = function(dom){
	if(dom.getAttribute('url')){
		var cache = {};
		var url = dom.getAttribute('url');
		$(dom).autocomplete({
			source : function(request,response){
			             
			             var term = request.term;
			             if(term in cache){
			            	 response(cache[term]);
			            	 return;
			             }
			             $.ajax({
			            	 url:url,
			            	 data:{keyword:$(dom).val()},
			            	 success:function(data){
			            		 var result = data.result;
			            		 var hasMore = data.hasMore;
			            		 if(result&&result.length<=0){
			            			 result.push({message:"没有匹配的结果!"});
			            		 }
			            		 if(hasMore){
			            			 result.push({message:"请输入更多查询信息..."});
			            		 }
			            	     response(result);
			                 }
			             });
		             },
		    focus: function( event, ui ) {
		            	 if(ui.item.message){
		            	 }
		            	 else{
		            	     $(dom).val( ui.item.label );
		            	 }
		 				return false;
		 			},
		 	select: function( event, ui ) {
		 				if(ui.item.message){
		 					//$(dom).val("");
		 				}
		 				else {
						    $(dom).val( ui.item.label );
		 				}
						return false;
					}
		})
		.data( "autocomplete" )._renderItem = function( ul, item ) {
			if(item.message){
				return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a style='color:#999;font-style:italic;'>"+item.message+"</a>" )
				.appendTo( ul );
			}
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a>" + item.label +"</a>" )
				.appendTo( ul );
		};
	}
}

util.isNumber = function(val)
{
  var reg = /^[\d|\.|,]+$/;
  return reg.test(val);
}

util.isInt = function(val)
{
  if (val == "")
  {
    return false;
  }
  var reg = /\D+/;
  return !reg.test(val);
}

util.isEmail = function( email )
{
  var reg1 = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;

  return reg1.test( email );
}

util.isTel = function ( tel )
{
  var reg = /^[\d|\-|\s|\_]+$/; //只允许使用数字-空格等

  return reg.test( tel );
}

util.fixEvent = function(e)
{
  var evt = (typeof e == "undefined") ? window.event : e;
  return evt;
}

util.srcElement = function(e)
{
  if (typeof e == "undefined") e = window.event;
  var src = document.all ? e.srcElement : e.target;

  return src;
}

util.isTime = function(val)
{
  var reg = /^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/;

  return reg.test(val);
}

util.x = function(e)
{ //当前鼠标X坐标
    return Browser.isIE?event.x + document.documentElement.scrollLeft - 2:e.pageX;
}

util.y = function(e)
{ //当前鼠标Y坐标
    return Browser.isIE?event.y + document.documentElement.scrollTop - 2:e.pageY;
}

util.request = function(url, item)
{
	var sValue=url.match(new RegExp("[\?\&]"+item+"=([^\&]*)(\&?)","i"));
	return sValue?sValue[1]:sValue;
}



function rowindex(tr)
{
  if (Browser.isIE)
  {
    return tr.rowIndex;
  }
  else
  {
    table = tr.parentNode.parentNode;
    for (i = 0; i < table.rows.length; i ++ )
    {
      if (table.rows[i] == tr)
      {
        return i;
      }
    }
  }
}

util.getEvent = function() //同时兼容ie和ff的写法 
{ 

	if(document.all) return window.event; 
	func=util.getEvent.caller; 
	while(func!=null){ 
	var arg0=func.arguments[0]; 
	if(arg0) 
	{ 
	if((arg0.constructor==Event || arg0.constructor ==MouseEvent) || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation)) 
	{ 
	return arg0; 
	} 
	} 
	func=func.caller; 
	} 
	return null; 

} 

document.getCookie = function(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0])
      return decodeURIComponent(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}

document.setCookie = function(sName, sValue, sExpires)
{
  var sCookie = sName + "=" + encodeURIComponent(sValue);
  if (sExpires != null)
  {
    sCookie += "; expires=" + sExpires;
  }

  document.cookie = sCookie;
}

document.removeCookie = function(sName,sValue)
{
  document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

function getPosition(o)
{
    var t = o.offsetTop;
    var l = o.offsetLeft;
    while(o = o.offsetParent)
    {
        t += o.offsetTop;
        l += o.offsetLeft;
    }
    var pos = {top:t,left:l};
    return pos;
}


function cleanWhitespace(element)
{
  var element = element;
  for (var i = 0; i < element.childNodes.length; i++) {
   var node = element.childNodes[i];
   if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
     element.removeChild(node);
   }
}

util.Map = function(){
	this.map = {};
}
util.Map.prototype = {
	put:function(key,value){
	    this.map[key] = value;
    },
    remove:function(key){
    	delete this.map[key];
    },
    get:function(key){
    	return this.map[key];
    }
}

util.checkImageFormat = function(dom){
	var fileext = dom.value.split('.')[1];
	fileext=fileext.toLowerCase();
	if ((fileext!='jpg')&&(fileext!='gif')&&(fileext!='jpeg')&&(fileext!='png')&&(fileext!='bmp')){
		alert("对不起，系统仅支持标准格式的照片，请您调整格式后重新上传，谢谢 ！");
		dom.focus();
	}
	else{
		document.getElementById("preview").innerHTML="图片预览区<img src='"+dom.value+"' style='border:6px double #ccc';padding:5px;>"
	}
} 